//
//  EnvironmentController.m
//  Water
//
//  Created by yh on 2017/12/27.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "EnvironmentController.h"
#import "AppClient.h"
@interface EnvironmentController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation EnvironmentController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [AppClient shared].servers.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    ServerModel *model = [AppClient shared].servers[indexPath.row];
    cell.textLabel.text = model.serverName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@:%@",model.host,model.port];
    cell.accessoryType = model == [AppClient shared].currentServer ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
    
    
    return cell;
}

- (IBAction)add:(id)sender {
    ServerModel *model = [[ServerModel alloc]init];
    model.serverName = self.name.text;
    model.host = self.host.text;
    model.port = self.port.text;
    [[AppClient shared].servers insertObject:model atIndex:0];
    [[AppClient shared] savePlans];
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ServerModel *model = [AppClient shared].servers[indexPath.row];
    [AppClient shared].currentServer = model;
    [[AppClient shared] savePlans];
    [self.tableView reloadData];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
     ServerModel *model = [AppClient shared].servers[indexPath.row];
    [[AppClient shared].servers removeObject:model];
    [[AppClient shared] savePlans];
    [self.tableView reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
